/**axios封装
 * 请求拦截、相应拦截、错误统一处理
 */
import axios from "axios";
import { Toast /*, Dialog */ } from "vant";
import encryptList from "./encryptList";
import configs from "@/configs/config.js";
import { methods } from "@/mixin";
// 请求超时时间
axios.defaults.timeout = 1000 * 300;
// 请求基础URL
axios.defaults.baseURL = configs.baseUrl;
process.env.NODE_ENV === "production" ? "/backend" : "/api-proxy";
const errorMessage = "系统异常，请稍后再试！";
axios.defaults.withCredentials = true;

axios.defaults.errorTip = true;
axios.defaults.encrypt = true;
axios.defaults.isLoading = true;
// post请求头
axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";
function requestEncrypt(config) {
  let a = document.createElement("a");
  a.href = config.url;

  //加密模块
  if (
    axios.defaults.encrypt &&
    encryptList.find(
      (v) =>
        (v.indexOf && v.indexOf(a.pathname) != -1) ||
        (v.test && v.test(a.pathname))
    )
  ) {
    config.headers["encrypt"] = "true";
    config.data = {
      bizContent: btoa(JSON.stringify(config.data || {})),
    };

  }
}
function responseDecrypt(response) {
  if (response?.headers?.["x-encrypt"] === "true") {
    try {
      response.data = JSON.parse(
        btoa(response.data.bizContent)
      );
    } catch (error) {
      Toast.fail(errorMessage);
      return Promise.reject(error);
    }
  }
  console.log(response.data);
}

axios.interceptors.request.use(
  (config) => {
    // console.log(1);
    config.headers["Accept"] = "application/json";
    config.headers["X-Requested-With"] = "XMLHttpRequest";
    let tokenId = methods.$getToken();
    if (tokenId) config.headers["Authorization"] = tokenId;
    if (config.method === "get") {
      config.data = true;

      Toast.loading({
        message: config.loadingMsg || "加载中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0,
      });
    } else {
      Toast.loading({
        message: config.loadingMsg || "加载中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0,
      });
    }

    if (config.method === "post") {
      //去除post.params
      config.params = {};
      if (!config.isFormData) {
        //添加{ indices: false } 参数
        // config.data = QS.stringify(config.data);
        //  'a[0]=1&a[1]=2&a[2]=3'
        // config.data = QS.stringify(config.data,{ indices: false });
        //  'a=1&a=2&a=3'
        // config.data = QS.stringify(config.data, { arrayFormat: 'indices' });
        //  'a[0]=1&a[1]=2&a[2]=3'
        // config.data = QS.stringify(config.data , { arrayFormat: 'brackets' });
        //  'a[]=1&a[]=2&a[]=3'
        // config.data = QS.stringify(config.data, { arrayFormat: 'repeat' } );
        //  'a=1&a=2&a=3'
      }

      requestEncrypt(config);
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export const codeFormat = (error, config) => {
  if (error) {
    if (error.message && error.message.includes("timeout")) {
      if (axios.defaults.errorTip && config.errorTip !== false) {
        Toast.fail("通讯请求超时，请稍后再试！");
      }
    } else if (error.message && error.message.includes("Network")) {
      if (axios.defaults.errorTip && config.errorTip !== false) {
        Toast.fail("网络未连接，请检查网络后再试！");
      }
    } else {
      if (axios.defaults.errorCodeFormat) {
        axios.defaults.errorCodeFormat(error, {
          errorMessage,
          ...config,
        });
      }
    }
  }
  // console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
  return Promise.reject({
    ...(error.response ? error.response : error),
    errorObj: error,
  });
};
// 响应拦截器
axios.interceptors.response.use(
  (response) => {
    Toast.clear();
    //解密模块
    responseDecrypt(response);
    if (
      axios.defaults.successCodeFormat &&
      axios.defaults.successCodeFormat(response)
    ) {
      let data = { ...response.data };

      return Promise.resolve({ ...response, data });
    } else {
      return codeFormat(response, response.config);
    }
  },
  (error) => {
    responseDecrypt(error?.response || {});
    Toast.clear();
    return codeFormat(error, error.config);
  }
  //服务器状态码不是200的情况
  // error => {}
);
/**
 * get方法，对应get请求
 */
export function get(url, params, info = "", config = {}) {
  return new Promise((resolve, reject) => {
    axios
      // .get(
      //   url + info,
      //   config || {
      //     params: params
      //   }
      // )
      .request({
        params,
        ...config,
        url: url + info,
        method: "get",
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
/**
 * post方法，对应post请求
 */
export function post(url, params = {}, info = "", config = null) {
  return new Promise((resolve, reject) => {
    axios
      // .post(url + info, config || params)
      .request({
        data: params,
        ...config,
        url: url + info,
        method: "post",
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

/**
 * 封装put请求
 */

export function put(url, params = {}, info = "", config = null) {
  return new Promise((resolve, reject) => {
    axios
      // .put(url + info, config || params)
      .request({
        data: params,
        ...config,
        url: url + info,
        method: "put",
      })
      .then(
        (res) => {
          resolve(res.data);
        },
        (err) => {
          reject(err);
        }
      );
  });
}

/**
 * 封装delete请求
 */
export function deletes(url, params = {}, info = "", config = null) {
  return new Promise((resolve, reject) => {
    axios
      // .delete(
      //   url + info,
      //   config || {
      //     data: params
      //   }
      // )
      .request({
        params,
        ...config,
        url: url + info,
        method: "delete",
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
